import { createStoreBindings } from "mobx-miniprogram-bindings";
import { globalStore } from "../../../store/index";
import {
  fetchOrders,
  acceptOrder,
  rejectOrder,
  startCooking,
  finishCooking,
  submitReview,
} from "../../../services/order";
import { toast } from "../../../utils/toast";
import { applyTabBar } from "../../../utils/tabBar";
import type { OrderRecord } from "../../../types/entities";

type OrderView = OrderRecord & {
  funTotal: number;
  statusLabel: string;
  statusDesc: string;
  createdText: string;
  updatedText: string;
};

const DINER_STATUS_META: Record<
  OrderRecord["status"],
  { label: string; desc: string }
> = {
  pending: { label: "待处理", desc: "厨师未接收" },
  accepted: { label: "已接收", desc: "厨师已确认，稍等开做" },
  rejected: { label: "已拒绝", desc: "" },
  cooking: { label: "制作中", desc: "美食正在出炉" },
  completed: { label: "已完成", desc: "快来评价这顿美味" },
};

const CHEF_TABS: Array<{ key: OrderRecord["status"]; title: string }> = [
  { key: "pending", title: "待处理" },
  { key: "accepted", title: "已接收" },
  { key: "cooking", title: "制作中" },
  { key: "completed", title: "已完成" },
  { key: "rejected", title: "已拒绝" },
];

Page({
  data: {
    isChef: globalStore.isChef,
    loading: true,
    currentOrders: [] as OrderView[],
    historyOrders: [] as OrderView[],
    chefOrders: [] as OrderView[],
    chefTabs: CHEF_TABS,
    chefActiveTab: "pending" as OrderRecord["status"],
    actionLoading: false,
    showReviewPanel: false,
    reviewOrderId: "",
    reviewRating: 5,
    reviewComment: "",
    reviewSubmitting: false,
    ratingOptions: [1, 2, 3, 4, 5],
    showRejectPanel: false,
    rejectOrderId: "",
    rejectReason: "",
    lastPromptedReviewId: "",
  },

  storeBindings: null as WechatMiniprogram.Component.TrivialInstance | null,

  onLoad() {
    this.storeBindings = createStoreBindings(this, {
      store: globalStore,
      fields: ["isChef"],
      actions: ["setOrders", "updateOrderSnapshot", "setActiveOrder"],
    });
  },

  onUnload() {
    this.storeBindings?.destroyStoreBindings?.();
  },

  async onShow() {
    await globalStore.initAppData();
    const isChef = globalStore.isChef;
    this.setData({ isChef });
    applyTabBar(isChef ? "chef" : globalStore.isDiner ? "diner" : "guest");
    await this.loadOrders();
  },

  async onPullDownRefresh() {
    await this.loadOrders();
    wx.stopPullDownRefresh();
  },

  async loadOrders(statusKey?: OrderRecord["status"]) {
    this.setData({ loading: true });
    try {
      if (this.data.isChef) {
        const activeKey = statusKey || this.data.chefActiveTab;
        const res = await fetchOrders({ role: "chef", status: activeKey });
        globalStore.setOrders(res.orders);
        const enriched = res.orders.map((order) => this.enrichOrder(order));
        this.setData({ chefOrders: enriched, chefActiveTab: activeKey });
      } else {
        const res = await fetchOrders({ role: "diner" });
        globalStore.setOrders(res.orders);
        const enriched = res.orders.map((order) => this.enrichOrder(order));
        const current = enriched.filter((order) =>
          ["pending", "accepted", "cooking"].includes(order.status)
        );
        const history = enriched.filter((order) =>
          ["completed", "rejected"].includes(order.status)
        );
        this.setData({ currentOrders: current, historyOrders: history });
        this.autoPopupReview(enriched);
      }
    } catch (error) {
      console.error("加载订单失败", error);
      wx.showToast({ title: "加载失败", icon: "none" });
    } finally {
      this.setData({ loading: false });
    }
  },

  enrichOrder(order: OrderRecord): OrderView {
    const funTotal = order.items.reduce(
      (sum, item) => sum + item.funValue * item.quantity,
      0
    );
    const statusMeta =
      DINER_STATUS_META[order.status] ||
      ({ label: order.status, desc: "" } as const);
    return {
      ...order,
      funTotal,
      statusLabel: statusMeta.label,
      statusDesc: statusMeta.desc,
      createdText: this.formatTime(order.createdAt),
      updatedText: this.resolveUpdateTime(order),
    };
  },

  resolveUpdateTime(order: OrderRecord) {
    if (order.status === "completed") {
      return this.formatTime(order.finishedAt || order.closedAt);
    }
    if (order.status === "cooking") {
      return this.formatTime(order.startedAt);
    }
    if (order.status === "accepted") {
      return this.formatTime(order.acceptedAt);
    }
    if (order.status === "rejected") {
      return this.formatTime(order.rejectedAt || order.closedAt);
    }
    return "";
  },

  formatTime(value?: string) {
    if (!value) return "";
    return value.replace("T", " ").slice(0, 16);
  },

  autoPopupReview(orderList: OrderView[]) {
    if (this.data.isChef) return;
    const target = orderList.find(
      (order) => order.status === "completed" && !order.review
    );
    if (!target) return;
    if (this.data.lastPromptedReviewId === target._id) return;
    this.setData({
      showReviewPanel: true,
      reviewOrderId: target._id,
      reviewRating: 5,
      reviewComment: "",
      lastPromptedReviewId: target._id,
    });
  },

  handleChefTabChange(event: WechatMiniprogram.BaseEvent) {
    if (!this.data.isChef) return;
    if (this.data.actionLoading) return;
    const { key } = event.currentTarget.dataset as {
      key: OrderRecord["status"];
    };
    if (!key || key === this.data.chefActiveTab) return;
    this.loadOrders(key);
  },

  async handleChefAccept(event: WechatMiniprogram.BaseEvent) {
    if (!this.data.isChef || this.data.actionLoading) return;
    const { id } = event.currentTarget.dataset as { id: string };
    if (!id) return;
    this.setData({ actionLoading: true });
    try {
      const res = await acceptOrder({ orderId: id });
      globalStore.updateOrderSnapshot(res.order);
      toast("已接单");
      await this.loadOrders();
    } catch (error) {
      console.error("接单失败", error);
      toast((error as Error).message || "操作失败");
    } finally {
      this.setData({ actionLoading: false });
    }
  },

  handleOpenRejectPanel(event: WechatMiniprogram.BaseEvent) {
    if (!this.data.isChef || this.data.actionLoading) return;
    const { id } = event.currentTarget.dataset as { id: string };
    if (!id) return;
    this.setData({
      showRejectPanel: true,
      rejectOrderId: id,
      rejectReason: "",
    });
  },

  handleRejectReasonInput(
    event: WechatMiniprogram.CustomEvent<{ value: string }>
  ) {
    const value = (event.detail.value || "").slice(0, 60);
    this.setData({ rejectReason: value });
  },

  handleCloseRejectPanel() {
    this.setData({
      showRejectPanel: false,
      rejectOrderId: "",
      rejectReason: "",
    });
  },

  async handleSubmitReject() {
    if (!this.data.isChef || this.data.actionLoading) return;
    if (!this.data.rejectOrderId) return;
    const reason = (this.data.rejectReason || "").trim();
    if (!reason) {
      toast("请填写拒绝原因");
      return;
    }
    this.setData({ actionLoading: true });
    try {
      const res = await rejectOrder({
        orderId: this.data.rejectOrderId,
        reason,
      });
      globalStore.updateOrderSnapshot(res.order);
      toast("已拒绝");
      this.handleCloseRejectPanel();
      await this.loadOrders();
    } catch (error) {
      console.error("拒绝失败", error);
      toast((error as Error).message || "操作失败");
    } finally {
      this.setData({ actionLoading: false });
    }
  },

  async handleChefStart(event: WechatMiniprogram.BaseEvent) {
    if (!this.data.isChef || this.data.actionLoading) return;
    const { id } = event.currentTarget.dataset as { id: string };
    if (!id) return;
    this.setData({ actionLoading: true });
    try {
      const res = await startCooking(id);
      globalStore.updateOrderSnapshot(res.order);
      toast("开始制作啦");
      await this.loadOrders();
    } catch (error) {
      console.error("开始制作失败", error);
      toast((error as Error).message || "操作失败");
    } finally {
      this.setData({ actionLoading: false });
    }
  },

  async handleChefFinish(event: WechatMiniprogram.BaseEvent) {
    if (!this.data.isChef || this.data.actionLoading) return;
    const { id } = event.currentTarget.dataset as { id: string };
    if (!id) return;
    this.setData({ actionLoading: true });
    try {
      const res = await finishCooking(id);
      globalStore.updateOrderSnapshot(res.order);
      toast("已完成");
      await this.loadOrders();
    } catch (error) {
      console.error("完成失败", error);
      toast((error as Error).message || "操作失败");
    } finally {
      this.setData({ actionLoading: false });
    }
  },

  handleViewDetail(event: WechatMiniprogram.BaseEvent) {
    const { id } = event.currentTarget.dataset as { id: string };
    if (!id) return;
    globalStore.setActiveOrder(id);
    wx.navigateTo({ url: `/pages/order/detail/index?id=${id}` });
  },

  handleOpenReview(event: WechatMiniprogram.BaseEvent) {
    if (this.data.isChef) return;
    const { id } = event.currentTarget.dataset as { id: string };
    if (!id) return;
    this.setData({
      showReviewPanel: true,
      reviewOrderId: id,
      reviewRating: 5,
      reviewComment: "",
    });
  },

  handleRatingChange(event: WechatMiniprogram.BaseEvent) {
    const { value } = event.currentTarget.dataset as { value: number };
    const rating = Math.min(5, Math.max(1, Number(value || 0)));
    this.setData({ reviewRating: rating });
  },

  handleReviewInput(event: WechatMiniprogram.CustomEvent<{ value: string }>) {
    const value = (event.detail.value || "").slice(0, 120);
    this.setData({ reviewComment: value });
  },

  handleCloseReview() {
    this.setData({
      showReviewPanel: false,
      reviewOrderId: "",
      reviewComment: "",
    });
  },

  async handleSubmitReview() {
    if (!this.data.reviewOrderId || this.data.reviewSubmitting) return;
    this.setData({ reviewSubmitting: true });
    try {
      const res = await submitReview({
        orderId: this.data.reviewOrderId,
        rating: this.data.reviewRating,
        comment: this.data.reviewComment,
      });
      globalStore.updateOrderSnapshot(res.order);
      toast("感谢评价");
      this.handleCloseReview();
      await this.loadOrders();
    } catch (error) {
      console.error("评价失败", error);
      toast((error as Error).message || "评价失败");
    } finally {
      this.setData({ reviewSubmitting: false });
    }
  },
});
